import os, qrcode, glob
from reportlab.pdfgen import canvas
from reportlab.lib.utils import ImageReader


def generate_contract_pdf(data_path, output_dir="合同输出"):
    os.makedirs(output_dir, exist_ok=True)
    for file in glob.glob(f"{data_path}/*.txt"):
        with open(file) as f:
            contract_data = f.read().split("|")
            qr = qrcode.make(contract_data[2]).get_image()  # 生成二维码[4]
            pdf = canvas.Canvas(f"{output_dir}/{contract_data[0]}.pdf")
            pdf.setFont("Helvetica", 12)
            pdf.drawString(50, 800, f"甲方：{contract_data[0]}")
            pdf.drawString(50, 780, f"金额：{contract_data[1]}万元")
            pdf.drawImage(ImageReader(qr), 400, 780, width=100, height=100)  # PDF排版[3]
            pdf.save()


# 调用示例
generate_contract_pdf("合同数据源")  # 只需这1行！